<template>
  <div class="content-area">
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <h2>活动日志管理</h2>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按用户id查询" value="userId"></el-option>
                <el-option label="按所属小区id查询" value="communityId"></el-option>
                <el-option label="按时间范围查询" value="timeRange"></el-option>
              </el-select>

              <el-input v-model="searchQuery" placeholder="请输入查询关键词" class="search-input" v-if="searchOption!== 'timeRange'"></el-input>
              <el-date-picker
                  v-model="timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="{
                shortcuts: false,
                format: 'yyyy-MM-dd',
                valueFormat: 'yyyy-MM-dd'
                }" v-if="searchOption === 'timeRange'"
              ></el-date-picker>
              <el-button type="primary" @click="searchUser" class="search-button">查询</el-button>
            </div>
          </div>
          <table v-if="userActivityLogForm && userActivityLogForm.data "
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr>
              <th style="width: 60px; height: 40px; border: 1px solid #eee;">日志id</th>
              <th style="width: 70px; height: 40px; border: 1px solid #eee;">用户id</th>
              <th style="width: 150px; height: 40px; border: 1px solid #eee;">活动详情</th>
              <th style="width: 100px; height: 40px; border: 1px solid #eee;">活动时间</th>
              <th style="width: 50px; height: 40px; border: 1px solid #eee;">涉及金额</th>
              <th style="width: 100px; height: 40px; border: 1px solid #eee;">日志类型</th>
              <th style="width: 100px; height: 40px; border: 1px solid #eee;">关联记录ID</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in userActivityLogForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 60px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 70px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.userId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 150px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.activityDetail" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.activityTime" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.amount" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.logType" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 30px; border: 1px solid #eee;">
                <el-input v-model="item.relatedRecordId" disabled class="disabled-style"></el-input>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
          <div v-else>暂无用户日志活动记录</div>
        </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="userActivityLogForm && userActivityLogForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[6, 8, 10]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="userActivityLogForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>

    </el-container>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { ElSwitch } from 'element-plus';
import moment from'moment'; // 引入 moment.js

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      userActivityLogForm: {
        id: "",
        userId: "",
        communityId: "",
        activityDetail: "",
        activityTime: "",
        amount: "",
        logType: "",
        relatedRecordId: ""
      },
      userStatisticsPage: null,
      errorMessage: '',
      currentPage: 1,
      pageSize: 10,
      originalInfo: null,
      searchQuery: '',
      formLabelWidth: '120px',
      searchOption: '',
      showDialog: false,
      communityId: localStorage.getItem('adminCommunityId') || '',
      communityName: localStorage.getItem('adminCommunityName') || '',
      ownerCount: 0,
      propertyCount: 0,
      timeRange: []
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    pageChange(url) {
      this.$router.push(url);
    },
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/activity-logs/page';
        let params = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        };
        if (this.searchOption === 'userId') {
          params.userId = this.searchQuery;
        } else if (this.searchOption === 'userType') {
          params.userType = this.searchQuery;
        }else if (this.searchOption === 'timeRange') {
          if (this.timeRange.length === 2) {
            const startTime = moment(this.timeRange[0]).format('YYYY-MM-DD');
            const endTime = moment(this.timeRange[1]).format('YYYY-MM-DD');
            params.startTime = startTime;
            params.endTime = endTime;
          }
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        this.userActivityLogForm = response.data;
        this.originalInfo = {...this.userActivityLogForm};
      } catch (error) {
        ElMessage.error('获取用户日志活动记录失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    async searchUser() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'userId') {
          const response = await axios.get('/api/activity-logs/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              userId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userActivityLogForm = response.data;
            this.originalInfo = {...this.userActivityLogForm };
          } else {
            ElMessage.error('查询用户活动日志信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'communityId') {
          const response = await axios.get('/api/activity-logs/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.userActivityLogForm = response.data;
            this.originalInfo = {...this.userActivityLogForm };
          } else {
            ElMessage.error('查询用户活动日志信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'timeRange') {
          let params ={
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            startTime: null,
            endTime: null
          };
          if (this.timeRange.length === 2) {
            const startTime = moment(this.timeRange[0]).format('YYYY-MM-DD');
            const endTime = moment(this.timeRange[1]).format('YYYY-MM-DD');
            params.startTime = startTime;
            params.endTime = endTime;
          }
          const response = await axios.get('/api/activity-logs/page', {
            headers: {
              Authorization: token
            },
            params: params
          });
          if (response.data.code === 200) {
            this.userActivityLogForm = response.data;
            this.originalInfo = {...this.userActivityLogForm };
          } else {
            ElMessage.error('查询用户活动日志信息失败,请输入正确信息');
          }
        }
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    }
  },
  mounted() {
    this.fetchData();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #eee;
  padding: 8px;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
.menu-header {
  padding: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 300px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}

.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}
</style>